package com.yuanfengerp.interceptor;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@CrossOrigin
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")){
            return true;
        }
        // 从HTTP请求头中获取名为"Authorization"的值，这通常用于携带认证信息，如JWT Token
        String token = request.getHeader("Authorization");
//        System.out.println("token = " + token);
        // 检查Token是否存在，并且是否以"Bearer "开头，这是JWT的标准格式，"Bearer "后面跟着实际的Token字符串
        if (token != null ){
//            token = token.substring(7);
            // 使用JWT解析器解析负载部分，"your_secret_key"是你的JWT密钥，用于验证Token的签名
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey("your_secret_key").parseClaimsJws(token);
            // 检查解析后的Claims对象是否为空，如果不为空，表示Token有效
            if (claimsJws.getBody() != null){
                // Token有效，返回true，允许请求继续处理
                return true;
            }
        }
        // 如果Token无效或不存在，返回false，请求将被拦截，不会继续处理
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // Token无效时的处理逻辑
        if (!preHandle(request, response, handler)) {
            // 如果preHandle方法返回false，表示Token无效
            response.setStatus(HttpStatus.UNAUTHORIZED.value()); // 设置HTTP响应状态码为401 Unauthorized
            response.getWriter().write("身份验证失败"); // 向响应体写入错误信息"Invalid Token"
            response.getWriter().flush(); // 刷新响应体内容
            response.getWriter().close(); // 关闭写入流
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 检查响应是否已经被提交
        if (!response.isCommitted()) {
            // 嬛忔璇锋眰瀹屾垚涔嬪悗娓呴櫎Token
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.removeAttribute("token");
            }
        } else {
            // 如果响应已经被提交，记录日志或采取其他措施
//            System.out.println("Response has already been committed, cannot modify session.");
        }
    }
}
